package com.ayic.garbagerecycle.service.impl;

import com.ayic.garbagerecycle.mapper.LoginMapper;
import com.ayic.garbagerecycle.pojo.LoginInfo;
import com.ayic.garbagerecycle.pojo.Result;
import com.ayic.garbagerecycle.pojo.User;
import com.ayic.garbagerecycle.service.LoginService;
import com.ayic.garbagerecycle.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImplement implements LoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public Result login(String username, String password) {
        // 1. 根据用户名查询用户
        User user = loginMapper.selectByUsername(username);
        LoginInfo loginInfo = new LoginInfo();
        if (user == null) {
            return Result.error("用户名或者密码错误");
        }

        // 2. 密码校验
        if (!user.getPassword().equals(password)) {
            return Result.error("用户名或者密码错误");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("user", username);
        data.put("role", user.getRole());

        loginInfo.setUsername(username);
        loginInfo.setRole(user.getRole());
        loginInfo.setToken(JwtUtils.generateToken(data));
        // 3. 登录成功
        return Result.success(loginInfo,"登录成功");
    }
}
